var rightSideView = function (root) {
  if (root == null) return [];
  let res = [];
  let queue = [root];
  while (queue.length !== 0) {
    let len = queue.length;
    while (len) {
      let node = queue.shift();
      // 当前一层的最后一个元素
      if (len == 1) res.push(node.val);
      if (node.left !== null) queue.push(node.left);
      if (node.right !== null) queue.push(node.right);
      len--;
    }
  }
  return res;
};

// 深度优先遍历
var rightSideView = function (root) {
  let res = [];
  if (!root) return res;
  dfs(root, 0, res);
  return res;
};

function dfs(root, depth, res) {
  if (root) {
    // 当数组长度等于当前深度时，把当前的值加入数组
    if (res.length === depth) {
      res.push(root.val);
    }
    // 先从右边开始，当右边没了，再轮到左边
    dfs(root.right, depth + 1, res);
    dfs(root.left, depth + 1, res);
  }
}
